package C039;

import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: C01
 * Package: C039
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/1/31 10:05
 * @Version 1.0
 * @Since 1.0
 */
public class C01 {
    public static void main(String[] args) {
        System.out.println(operator("1*(1+2)+4/2-1"));
        System.out.println(operator("1+2*2/3+1"));
        System.out.println(operator("(1+2-(2*2))"));
    }


    static int where = 0;

    public static int operator(String express) {
        where = 0;
        return process(express.toCharArray());
    }

    private static int process(char[] charArray) {
        List<Integer> nums = new ArrayList<Integer>();
        List<Character> op = new ArrayList<Character>();
        int res = 0;
        int cur = 0;
        while (where < charArray.length && charArray[where] != ')') {
            if (charArray[where] == '(') {
                where++;
                cur = process(charArray);
            } else if (charArray[where] >= '0' && charArray[where] <= '9') {
                cur += cur * 10 + (charArray[where] - '0');
                where++;
            } else { // 一定是 符号
                push(charArray[where], cur, nums, op);
                cur = 0;
                where++;
            }
        }
        where++;
        // 处理最后一个num的压入
        push('+', cur, nums, op);
        // 这里的全部都是加减
        res += compute(nums, op);
        return res;
    }

    private static int compute(List<Integer> nums, List<Character> ops) {
        int size = nums.size();
        Integer num = nums.get(0);
        Character op = ops.get(0);
        Integer num2 = 0;
        int res = num;
        for (int i = 1; i < size; i++) {
            num2 = nums.get(i);
            res += (op == '+') ? num2 : -num2;
            op = ops.get(i);
        }
        return res;
    }

    private static void push(char c, int cur, List<Integer> nums, List<Character> ops) {
        int size = nums.size();

        if (size == 0 || ops.get(size - 1) == '+' || ops.get(size - 1) == '-') {
            nums.add(cur);
            ops.add(c);
            return;
        }
        char op = ops.get(size - 1);
        int num = nums.get(size - 1);
        if (op == '*') {
            cur = num * cur;
        } else {
            cur = num / cur;
        }
        nums.set(size - 1, cur);
        ops.set(size - 1, c);
    }
}
